package cn.openea.perpartner.componet.web.service.impl;

import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.RegexUtil;
import cn.openea.perpartner.common.core.utils.SpringContextUtils;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.componet.constant.CommonConstants;
import cn.openea.perpartner.componet.util.UserContext;
import cn.openea.perpartner.componet.web.entity.SmsBlacklist;
import cn.openea.perpartner.componet.web.entity.vo.SmsBlacklistVo;
import cn.openea.perpartner.componet.web.mapper.SmsBlacklistMapper;
import cn.openea.perpartner.componet.web.service.ISmsBlacklistService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service("smsBlacklistService")
public class SmsBlacklistServiceImpl extends ServiceImpl<SmsBlacklistMapper, SmsBlacklist> implements ISmsBlacklistService {

    @Autowired
    private RedisCache redisCache;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SmsBlacklist smsBlacklist) {
        // 判断是否存在
        if (StringUtils.isBlank(smsBlacklist.getPhone())) {
            throw new ServiceException("手机号不能为空");
        }
        if (!RegexUtil.matchCellphone(smsBlacklist.getPhone())) {
            throw new ServiceException("手机号码格式不正确");
        }
        if (this.isExist(smsBlacklist.getPhone())) {
            throw new ServiceException("手机号已存在黑名单中");
        }
        smsBlacklist.setCreateUserId(UserContext.getUserId());
        save(smsBlacklist);
        // 更改缓存
        Boolean keyExist = redisCache.hasKey(CommonConstants.REDIS_KEY.SMS_PHONE_BLACKLIST);
        if (keyExist != null && keyExist) {
            // 添加缓存
            redisCache.addToCacheList(CommonConstants.REDIS_KEY.SMS_PHONE_BLACKLIST, smsBlacklist.getPhone());
            return;
        }
        cacheList();
    }

    @Override
    public List<SmsBlacklist> selectListByVo(SmsBlacklistVo smsBlacklistVo) {
        return baseMapper.selectList(buildWrapper(smsBlacklistVo, true));
    }

    private LambdaQueryWrapper<SmsBlacklist> buildWrapper(SmsBlacklistVo smsBlacklistVo, boolean isSort) {
        LambdaQueryWrapper<SmsBlacklist> queryWrapper = new LambdaQueryWrapper<>();
        if (isSort) {
            queryWrapper.orderByDesc(SmsBlacklist::getCreateTime);
        }
        if (smsBlacklistVo == null) {
            return queryWrapper;
        }
        if (StringUtils.isNotBlank(smsBlacklistVo.getPhone())) {
            queryWrapper.like(SmsBlacklist::getPhone, smsBlacklistVo.getPhone());
        }
        return queryWrapper;
    }

    @Override
    public boolean isExist(String phone) {
        if (StringUtils.isBlank(phone)) {
            return false;
        }
        List<String> phoneBlacklist = redisCache.getCacheList(CommonConstants.REDIS_KEY.SMS_PHONE_BLACKLIST);
        return phoneBlacklist.contains(phone);
    }

    @Override
    public void cacheList() {
        List<SmsBlacklist> smsBlacklists = baseMapper.selectList(null);
        // 获取所有的黑名单中的手机号
        List<String> phoneBlacklist = smsBlacklists
                .parallelStream()
                .map(SmsBlacklist::getPhone)
                .collect(Collectors.toList());
        // 先删除这个key
        redisCache.deleteObject(CommonConstants.REDIS_KEY.SMS_PHONE_BLACKLIST);
        redisCache.setCacheList(CommonConstants.REDIS_KEY.SMS_PHONE_BLACKLIST, phoneBlacklist);
    }

    @Override
    public void deleteByIds(@NonNull List<Long> ids) {
        if (ids.isEmpty()) {
            return;
        }
        ids.forEach(id -> {
            ISmsBlacklistService smsBlacklistService =(ISmsBlacklistService) SpringContextUtils.getBean("smsBlacklistService");
            smsBlacklistService.deleteById(id);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        String phone = baseMapper.findPhoneById(id);
        if (StringUtils.isBlank(phone)) {
            return;
        }
        // 删除这个黑名单
        baseMapper.deleteById(id);
        // 删除redis的缓存
        redisCache.removeCacheList(CommonConstants.REDIS_KEY.SMS_PHONE_BLACKLIST, phone);
    }
}